//
//  ViewController.m
//  LCOpenSDKDemo
//
//  Created by chenjian on 16/7/11.
//  Copyright (c) 2016年 lechange. All rights reserved.
//

#import "AdminModeViewController.h"
#import "HintViewController.h"
#import "StartViewController.h"

#import "UserModeViewController.h"

@interface StartViewController ()

@end

@implementation StartViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    UIImage* img = [UIImage imageNamed:@"icon_admin.png"];
    [self.m_btnMan setBackgroundImage:img forState:UIControlStateNormal];
    [self.m_btnMan setTitle:@"" forState:UIControlStateNormal];

    UIImage* imgUser = [UIImage imageNamed:@"icon_user.png"];
    [self.m_btnUser setTitle:@"" forState:UIControlStateNormal];
    [self.m_btnUser setBackgroundImage:imgUser forState:UIControlStateNormal];

    [self.m_textAppId setDelegate:self];
    [self.m_textAppSecret setDelegate:self];

    self.m_textAppId.text = @"xxxxxxxxxxxxxxxx";
    self.m_textAppSecret.text = @"xxxxxxxxxxxxxxxx";

    self.m_textServerInfo.text = @"openapi.lechange.cn:443";
    self.m_textServerInfo.delegate = self;

    //get info
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString* libraryDirectory = [paths objectAtIndex:0];

    NSString* myDirectory = [libraryDirectory stringByAppendingPathComponent:@"lechange"];
    NSString* davDirectory = [myDirectory stringByAppendingPathComponent:@"openSDK"];

    NSString* infoPath = [davDirectory stringByAppendingPathComponent:@"info"];
    NSString* realPath = [infoPath stringByAppendingString:@".txt"];
    NSFileManager* fileManage = [NSFileManager defaultManager];
    NSError* pErr;
    BOOL isDir;
    if (NO == [fileManage fileExistsAtPath:myDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:myDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }
    if (NO == [fileManage fileExistsAtPath:davDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:davDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }
    if (YES == [fileManage fileExistsAtPath:realPath isDirectory:&isDir]) {
        NSLog(@"%@ exists,isdir[%d]", realPath, isDir);
        NSString* content = [NSString stringWithContentsOfFile:realPath encoding:NSUTF8StringEncoding error:nil];
        char appId[500] = { 0 };
        char appSecret[500] = { 0 };
        char svrInfo[500] = { 0 };
        char appAccount[500] = { 0 };
        NSLog(@"content %s", [content UTF8String]);
        sscanf([content UTF8String], "[%[^]]][%[^]]][%[^]]]%*s", appId, appSecret, svrInfo);
        self.m_textAppId.text = [NSString stringWithUTF8String:appId];
        self.m_textAppSecret.text = [NSString stringWithUTF8String:appSecret];
        self.m_textServerInfo.text = [NSString stringWithUTF8String:svrInfo];

        NSLog(@"appid[%@],appsecret[%@],account[%s],svrInfo[%s]", self.m_textAppId.text, self.m_textAppSecret.text, appAccount, svrInfo);
    }
    //end
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onManagerMode:(id)sender
{
    //save info
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString* libraryDirectory = [paths objectAtIndex:0];

    NSString* myDirectory = [libraryDirectory stringByAppendingPathComponent:@"lechange"];
    NSString* davDirectory = [myDirectory stringByAppendingPathComponent:@"openSDK"];

    NSString* infoPath = [davDirectory stringByAppendingPathComponent:@"info"];
    NSString* realPath = [infoPath stringByAppendingString:@".txt"];

    NSFileManager* fileManage = [NSFileManager defaultManager];
    NSError* pErr;
    BOOL isDir;
    if (NO == [fileManage fileExistsAtPath:myDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:myDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }
    if (NO == [fileManage fileExistsAtPath:davDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:davDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }

    NSString* textTmp = [NSString stringWithFormat:@"[%@][%@][%@]", self.m_textAppId.text, self.m_textAppSecret.text, self.m_textServerInfo.text];
    [textTmp writeToFile:realPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    //end

    if (nil == self.m_textAppId.text || 0 == self.m_textAppId.text.length
        || nil == self.m_textAppSecret.text || 0 == self.m_textAppSecret.text.length) {
        UIStoryboard* currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HintViewController* hintView = [currentBoard instantiateViewControllerWithIdentifier:@"HintView"];
        [hintView setInfo:self.m_textAppId.text appSecret:self.m_textAppSecret.text info:@"提示：当前demo中未正确配置appId和appSecret，请登录开放平台门户站点，创建应用（应用创建后会得到App ID和App Secret），并且根据开发中心>开发指南中的提示，在demo的源码中的相应代码中填写appId和appSecret，设置后再次编译此demo，进行真机调试。"];
        [self.navigationController pushViewController:hintView animated:NO];
        return;
    }

    UIStoryboard* currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    AdminModeViewController* adminModeView = [currentBoard instantiateViewControllerWithIdentifier:@"AdminModeView"];

    [adminModeView setAppIdAndSecret:self.m_textAppId.text appSecret:self.m_textAppSecret.text svr:[self parseServerIp:self.m_textServerInfo.text] port:[self parseServerPort:self.m_textServerInfo.text]];
    [self.navigationController pushViewController:adminModeView animated:NO];
}
- (void)onUserMode:(id)sender
{
    //save info
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString* libraryDirectory = [paths objectAtIndex:0];

    NSString* myDirectory = [libraryDirectory stringByAppendingPathComponent:@"lechange"];
    NSString* davDirectory = [myDirectory stringByAppendingPathComponent:@"openSDK"];

    NSString* infoPath = [davDirectory stringByAppendingPathComponent:@"info"];
    NSString* realPath = [infoPath stringByAppendingString:@".txt"];

    NSFileManager* fileManage = [NSFileManager defaultManager];
    NSError* pErr;
    BOOL isDir;
    if (NO == [fileManage fileExistsAtPath:myDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:myDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }
    if (NO == [fileManage fileExistsAtPath:davDirectory isDirectory:&isDir]) {
        [fileManage createDirectoryAtPath:davDirectory withIntermediateDirectories:YES attributes:nil error:&pErr];
    }

    NSString* textTmp = [NSString stringWithFormat:@"[%@][%@][%@]", self.m_textAppId.text, self.m_textAppSecret.text, self.m_textServerInfo.text];
    [textTmp writeToFile:realPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    //end

    if (nil == self.m_textAppId.text || 0 == self.m_textAppId.text.length
        || nil == self.m_textAppSecret.text || 0 == self.m_textAppSecret.text.length) {
        UIStoryboard* currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HintViewController* hintView = [currentBoard instantiateViewControllerWithIdentifier:@"HintView"];

        [self.navigationController pushViewController:hintView animated:NO];
        [hintView setInfo:self.m_textAppId.text appSecret:self.m_textAppSecret.text info:@"提示：当前demo中未正确配置appId和appSecret，请登录开放平台门户站点，创建应用（应用创建后会得到App ID和App Secret），并且根据开发中心>开发指南中的提示，在demo的源码中的相应代码中填写appId和appSecret，设置后再次编译此demo，进行真机调试。"];
        return;
    }

    UIStoryboard* currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    UserModeViewController* userModeView = [currentBoard instantiateViewControllerWithIdentifier:@"UserModeView"];

    [userModeView setAppIdAndSecret:self.m_textAppId.text appSecret:self.m_textAppSecret.text svr:[self parseServerIp:self.m_textServerInfo.text] port:[self parseServerPort:self.m_textServerInfo.text]];
    [self.navigationController pushViewController:userModeView animated:NO];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField
{
    CGFloat offset = self.view.frame.size.height - (textField.frame.origin.y + textField.frame.size.height + 216 + 50);
    if (offset <= 0) {
        [UIView animateWithDuration:0.1 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = offset;
            self.view.frame = frame;
        }];
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField*)textField
{
    [UIView animateWithDuration:0.1 animations:^{
        CGRect rect = self.view.frame;
        rect.origin.y = 0;
        self.view.frame = rect;
    }];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (NSString*)parseServerIp:(NSString*)svrInfo
{
    NSArray* arr = [svrInfo componentsSeparatedByString:@":"];
    NSLog(@"parseServerIP[%@],ip[%@]", arr, [arr objectAtIndex:0]);
    return [arr objectAtIndex:0];
}
- (NSInteger)parseServerPort:(NSString*)svrInfo
{
    NSArray* arr = [svrInfo componentsSeparatedByString:@":"];
    NSLog(@"parseServerport[%@]", arr);
    if (arr.count <= 1) {
        if ([[arr objectAtIndex:0] rangeOfString:@"https"].location != NSNotFound) {
            return 443;
        }
        else {
            return 80;
        }
    }
    else {
        return [[arr objectAtIndex:1] intValue];
    }
}
@end
